package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;


@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //1.检查参数
        if (dto==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //2.分页
        IPage page = new Page(dto.getPage(),dto.getSize());
        //3.根据状态查询
        LambdaQueryWrapper<ApUserRealname> queryWrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus()!=null) {
            queryWrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage resultPage = page(page, queryWrapper);
        //3.封装返回结果
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), resultPage.getTotal());
        result.setData(resultPage.getRecords());
        return result;
    }
    @Autowired
    ApUserMapper apUserMapper;
    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    ArticleFeign articleFeign;
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        //1.检查参数
        if (dto==null||dto.getId()==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询实名认证信息
        ApUserRealname userRealname = getById(dto.getId());
        //3.判断当前实名认证的状态（status=1）
        if (userRealname==null||userRealname.getStatus().intValue()!=1) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        //4.查询相关连的ApUser用户
        ApUser apUser = apUserMapper.selectById(dto.getId());
        if (apUser==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的App用户不存在");
        }
        //5.修改实名认证的用户信息
        userRealname.setStatus(status);
        userRealname.setUpdatedTime(new Date());
        if (StringUtils.isNotBlank(dto.getMsg())) {
            userRealname.setReason(dto.getMsg());
        }
        updateById(userRealname);
        if (status.intValue()==2) {
            return ResponseResult.okResult();
        }
        //审核通过，创建自媒体账户，创建作者信息
        WmUser wmUser = creatWeMediaUser(apUser);
        creatAuthUser(wmUser,apUser);
       // int i = 1/0;
        //6.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void creatAuthUser(WmUser wmUser, ApUser apUser) {
        //1.检查作者信息是否存在
        ResponseResult<ApAuthor> result = articleFeign.findByUserId(apUser.getId());
        if (result.getCode()!=0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,result.getErrorMessage());
        }
        ApAuthor apAuthor = result.getData();
        if (apAuthor!=null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"对应的作者信息已经存在");
        }
        //2.添加作者信息
        apAuthor = new ApAuthor();
        apAuthor.setCreatedTime(new Date());
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(2); // 自媒体人类型
        apAuthor.setUserId(wmUser.getApUserId()); // APP 用户ID
        apAuthor.setWmUserId(wmUser.getId()); // 自媒体用户ID
        //3.保存作者信息
        ResponseResult save = articleFeign.save(apAuthor);
        if (save.getCode()!=0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,result.getErrorMessage());
        }

    }

    private WmUser creatWeMediaUser(ApUser apUser) {
        //1.检查自媒体用户是否存在，不存在则创建
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());

        if (result.getCode()!=0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,result.getErrorMessage());
        }
        WmUser wmUser = result.getData();
        if (wmUser!=null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"对应的自媒体用户已经存在");
        }
        //巨坑，此处需要初始化user对象，因为上行代码判断wmUser为空，如果不初始化会报空指针异常
        wmUser = new WmUser();
        wmUser.setName(apUser.getName());
        wmUser.setSalt(apUser.getSalt());  // 盐
        wmUser.setPassword(apUser.getPassword()); // 密码
        wmUser.setPhone(apUser.getPhone());
        wmUser.setCreatedTime(new Date());
        wmUser.setType(0); // 个人
        wmUser.setApUserId(apUser.getId());  // app端用户id
        wmUser.setStatus(AdminConstants.PASS_AUTH.intValue());
        ResponseResult<WmUser> save = wemediaFeign.save(wmUser);
        if (save.getCode()!=0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,result.getErrorMessage());
        }
        return save.getData();
    }
}
